<template>
  <div class="devops-config">
    <div class="left">
      <Menu :active-name="0" ref="menu" @on-select="menuSelect">
        <MenuItem v-for="(t, i) in environmentList" :name="i" :key="i">{{ t.centerName }}</MenuItem>
      </Menu>
    </div>
    <!--右侧 -->
    <div class="right search">
      <div class="search_top">
        <div class="search_top_statis" @click="toDetail">
          <div class="tip">
            <Tag color="gold">近30天</Tag>
          </div>
          <div class="cell">
            <label>
              未执行：
              <!--引入svg-icon图标 -->
              <svg-icon type="qq" size="30"></svg-icon>
              <!--引入iconfont图标,可以更改颜色 or 字体 -->
              <!-- <Icon custom="icon-qq icon-qq-color" size="30" /> -->
              <span style="color:#c5c8ce">
                {{
                prepareCount | toThousands
                }}
              </span>
            </label>
          </div>
          <div class="cell">
            <label>
              执行中：
              <span style="color:#19be6b">213</span>
            </label>
          </div>
          <div class="cell">
            <label>
              已完成：
              <span style="color:#2db7f5">0</span>
            </label>
          </div>
          <div class="cell">
            <label>
              异常已回滚：
              <span style="color:#ed4014">0</span>
            </label>
          </div>
        </div>
        <div class="search_top_deal">
          <Input
            search
            placeholder="请输入要查找的marathon id"
            style="width:350px;"
            enter-button
            v-model="keyWord"
          />
          <Button type="primary" @click.native="submit" :disabled="!changeList.length">确认提交</Button>
        </div>
      </div>
      <div class="search_table mt-10 mb-15">
        <!--iview自带的scroll -->
        <Scroll :height="scrollH" :on-reach-bottom="handleReachBottom">
          <!--dl,dt,dd 又叫表格标签，与table表格类似组合标签 -->
          <dl class="table_list">
            <!--标题 -->
            <dt>
              <Row align="middle">
                <Col span="12">
                  <span class="name">Marathon id</span>
                </Col>
                <Col span="12">
                  <span class="version">版本</span>
                </Col>
              </Row>
            </dt>
            <!--内容 -->
            <dd v-for="(t, i) in list" :key="i">
              <Row align="middle">
                <Col span="12">
                  <span class="name mr-5">{{ t.marathonId }}</span>
                  <Tag color="primary" v-show="t.version && t.version !== t.oldVersion">未提交</Tag>
                </Col>
                <Col span="12">
                  <Select v-model="t.version" style="width:200px">
                    <Option
                      v-for="(child, i) in t.versions"
                      :key="i"
                      :value="child.version"
                    >{{child.version }}</Option>
                  </Select>
                </Col>
              </Row>
            </dd>
          </dl>
        </Scroll>
        <!--backtop -->
        <BackTop target=".ivu-scroll-container" :visibilityHeight="20" :right="30" :bottom="40"></BackTop>
      </div>
    </div>
  </div>
</template>
<script>
import BackTop from "@components/back-top";
import { queryEnvironment, queryApp, getUagReloadOutline } from "@api/service";
import { toThousands } from "@libs/tools";
import { findComponentUpward } from "@libs/assist";
let timer = null;
export default {
  components: {
    BackTop
  },
  name: "DevopsConfig",
  filters: {
    toThousands: toThousands
  },
  data() {
    return {
      loading: false,
      hasMore: true, //是否将所有的数据加载完毕,若完毕则hasMore=false，即为了控制不再请求接口
      scrollH: 0,
      keyWord: "",
      list: [],
      environmentList: [],
      dataCenterCode: "10000", //临时设置默认值
      prepareCount: 0
    };
  },
  computed: {
    queryListParams() {
      return {
        pageNumber: 1,
        pageSize: 20,
        dataCenterCode: this.dataCenterCode,
        keyWord: this.keyWord
      };
    },
    changeList() {
      //过滤未提交的版本
      return this.list.filter(it => it.version && it.oldVersion !== it.version);
    }
  },
  watch: {
    loading(now) {
      this.setLoading(now);
    }
  },
  methods: {
    setLoading(status) {
      findComponentUpward(this, "Home").loading = status;
    },
    //左侧菜单
    menuSelect(name) {
      this.setCode(name);
      this.queryListFirst();
    },
    async getUagReloadOutline() {
      this.loading = true; //定时刷新检测watch，即loading图标显示
      const [err, data] = await getUagReloadOutline({
        dataCenterCode: this.dataCenterCode
      });
      this.loading = false; //检测watch
      if (err) {
        this.errors(err);
        return;
      }
      //注意写法
      const { prepareCount } = data;
      this.prepareCount = prepareCount;
    },

    //定时执行
    loopGetUagReloadOutline() {
      clearTimeout(timer);
      this.getUagReloadOutline();
      timer = setTimeout(() => {
        this.loopGetUagReloadOutline();
      }, 5000);
    },

    async initQuery() {
      await this.queryEnvironment();
      this.loopGetUagReloadOutline();
      await this.queryListFirst();
    },
    //第一次初始化加载
    queryListFirst() {
      this.hasMore = true;
      this.queryListParams.pageNumber = 1;
      this.queryList(true);
    },
    //请求列表接口
    async queryList(replace = false) {
      if (!this.hasMore) return;
      const [err, data] = await queryApp(this.queryListParams);
      if (err) {
        this.errors(err || "获取列表错误");
        return;
      }
      const { pageNumber, pageSize, totalSize, rows } = data;
      if (totalSize > pageNumber * pageSize) {
        this.queryListParams.pageNumber++;
      } else {
        this.hasMore = false;
      }
      if (replace) {
        //第一次加载列表
        this.list = this.dealApplist(rows);
      } else {
        //滚动下拉加载列表
        this.list = this.list.concat(this.dealApplist(rows));
      }
    },

    //处理数据转换
    dealApplist(data, setVersion = true) {
      return data.map(it => {
        const selected = it.versions.filter(t => t.selected === true);
        let version = "";
        if (selected.length) version = selected[0].version;
        return {
          ...it,
          version,
          oldVersion: setVersion ? version : it.oldVersion
        };
      });
    },
    // scroll滚动到底部触发事件
    handleReachBottom() {
      this.queryList();
    },
    toDetail() {
      this.$router.push({
        name: "detail",
        query: {
          dataCenterCode: this.dataCenterCode
        }
      });
    },
    //获取左侧列表
    async queryEnvironment() {
      if (this.listLoading) return;
      this.listLoading = true;
      const [err, data] = await queryEnvironment();
      this.listLoading = false;
      if (err) {
        const msg = err || "获取列表错误";
        this.errors(msg);
        return;
      }
      this.environmentList = data;
      //this.setCode();
      //更新menu菜单选中
      this.$nextTick(this.$refs.menu.updateActiveName);
    },
    //传递参数
    setCode(name = 0) {
      this.dataCenterCode = this.environmentList[name].centerCode;
    },
    //固定展示区域
    setHeight() {
      this.$nextTick(() => {
        //vue中获取dom的方法,HTML5向Web API新引入了 document.querySelector()和document.querySelectorAll()两个方法,从DOM中选取元素
        this.scrollH = this.$el
          .querySelector(".search_table")
          .getBoundingClientRect().height;
      });
    },

    //确认提交
    submit() {}
  },
  mounted() {
    this.setHeight();
  },
  beforeDestroy() {
    clearTimeout(timer);
  },

  /**
   * 改写定时器的处理方式
   * mounted() {
      const timer = setInterval(() => { ... }, 1000);
      this.$once('hook:beforeDestroy', () => clearInterval(timer);)
    } 
   */

  activated() {
    //mounted(只执行一次)--->进入activated---->离开deactivated
    if (this.$route.meta.isBack) {
      this.initQuery();
      this.$route.meta.isBack = false;
    }
  },
  deactivated() {
    clearTimeout(timer);
  }
};
</script>
<style lang="stylus" scoped>
.devops-config {
  height: 100%
  box-sizing: border-box
  position: relative
  .left {
    width: 240px
    height: 100%
    float: left
    overflow: auto
    >>>.ivu-menu {
      height: inherit // 左侧的分割线
      overflow: inherit
    }
  }
  .search_table {
    position: relative
  }
  .search {
    height: 100%
    margin-left: 255px
    display: flex
    flex-direction: column
    >>>.ivu-scroll-container {
      overflow-y: auto
    }
    &_top {
      &_deal {
        margin: 15px 0
        display: flex
        justify-content: space-between
      }
      &_statis {
        position: relative
        height: 80px
        background: #ebf5ff
        border-radius: 5px 5px 0 0
        display: flex
        align-items: center
        justify-content: space-evenly
        .tip {
          position: absolute
          top: 0
          left: 0
        }
        .cell {
          font-size: 16px
          label {
            cursor: pointer
            >span {
              font-size: 30px
            }
          }
        }
      }
    }
    &_table {
      flex-grow: 1 // flex-grow:1，则它们将等分剩余空间
      overflow-y: auto
    }
  }
  .table_list {
    dt {
      background: #f8f8f9
    }
    dd, dt {
      padding: 5px
      line-height: 32px
      border-bottom: 1px solid #e8eaec
    }
  }
  .icon-qq-color {
    color: #ffe58f
  }
}
</style>
